package com.example.bookkeep.login;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bookkeep.MainActivity;
import com.example.bookkeep.R;
import com.example.bookkeep.Utils.OkHttpUtil;
import com.example.bookkeep.Utils.URLUtils;

import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 登录活动，处理用户登录逻辑
 */
public class LoginActivity extends AppCompatActivity {

    // 用户名输入框
    private EditText etUsername;
    // 密码输入框
    private EditText etPassword;
    // 记住我复选框
    private CheckBox cbRememberMe;

    /**
     * 初始化登录界面
     * @param savedInstanceState 保存的实例状态
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 绑定用户名输入框
        etUsername = findViewById(R.id.etUsername);
        // 绑定密码输入框
        etPassword = findViewById(R.id.etPassword);
        // 绑定记住我复选框
        cbRememberMe = findViewById(R.id.cbRememberMe);
        // 绑定登录按钮，并设置点击监听器
        Button btnLogin = findViewById(R.id.btnLogin);

        SharedPreferences sp = getSharedPreferences("auth", MODE_PRIVATE);
        if (sp.getBoolean("remember", false)) {
            etUsername.setText(sp.getString("username", ""));
            etPassword.setText(sp.getString("password", ""));
            cbRememberMe.setChecked(true);
        }


        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

        TextView tvRegister = findViewById(R.id.tvRegister);
        TextView tvForgotPassword = findViewById(R.id.tvForgotPassword);

        tvRegister.setOnClickListener(v -> {
            // 跳转到注册页面
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });

        tvForgotPassword.setOnClickListener(v -> {
            // 跳转到找回密码页面
            Intent intent = new Intent(LoginActivity.this, VerifyEmailActivity.class);
            startActivity(intent);
        });

    }

    /**
     * 执行登录操作
     */
    private void login() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences sp = getSharedPreferences("auth", MODE_PRIVATE);

        if (cbRememberMe.isChecked()) {
            sp.edit()
                    .putString("username", username)
                    .putString("password", password)
                    .putBoolean("remember", true)
                    .apply();
        } else {
            sp.edit()
                    .remove("username")
                    .remove("password")
                    .remove("remember")
                    .apply();
        }

        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("username", username);
                jsonObject.put("password", password);

                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(jsonObject.toString(), JSON);

                Request request = new Request.Builder()
                        .url(URLUtils.BASE_URL + "/user/login")
                        .post(body)
                        .build();

                OkHttpClient client = OkHttpUtil.getInstance();
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject result = new JSONObject(responseBody);
                    int code = result.getInt("code");
                    String message = result.getString("message");

                    runOnUiThread(() -> {
                        if (code == 1) {
                            try {
                                JSONObject content = result.getJSONObject("content");
                                String token = content.getString("token");
                                int userId = content.getInt("userId");

                                // 保存 token 和 userId
                                sp.edit()
                                        .putString("token", token)
                                        .putInt("userId", userId)
                                        .apply();


                                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                                // 跳转到主页
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();

                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(this, "解析服务器响应失败", Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(this, "登录失败：" + message, Toast.LENGTH_SHORT).show();
                        }
                    });

                } else {
                    runOnUiThread(() -> Toast.makeText(this, "网络请求失败", Toast.LENGTH_SHORT).show());
                }

            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> Toast.makeText(this, "请求异常: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        }).start();
    }


}
